package com.sg.business.management.dnd;

import java.util.List;

import org.eclipse.swt.dnd.DropTargetEvent;

import com.mobnut.db.model.IContext;
import com.mobnut.db.model.PrimaryObject;
import com.sg.business.model.DocumentDefinition;
import com.sg.business.model.FolderDefinition;
import com.sg.widgets.MessageUtil;
import com.sg.widgets.commons.dnd.DropPrimaryObjectTarget;
import com.sg.widgets.part.CurrentAccountContext;
import com.sg.widgets.viewer.CTreeViewer;
import com.sg.widgets.viewer.ViewerControl;

public class DropFolderDefAndDocumentDef extends DropPrimaryObjectTarget {

	@Override
	protected void doDrop(String sourceId, List<PrimaryObject> dragsItems,
			DropTargetEvent event, ViewerControl targetViewerControl) {
		if (dragsItems == null || dragsItems.isEmpty()) {
			return;
		}
		if (event.item == null) {
			return;
		}
		try {
			Object targetPo = event.item.getData();
			if (targetPo instanceof FolderDefinition) {
				FolderDefinition targetFolderDef = (FolderDefinition) targetPo;
				targetFolderDef.checkCancelDrop(dragsItems);
				IContext context = new CurrentAccountContext();
				for (PrimaryObject po : dragsItems) {
					FolderDefinition parentFolderDef = null;
					if (po instanceof FolderDefinition) {
						FolderDefinition folderd = (FolderDefinition) po;
						parentFolderDef = folderd.getParentFolderDefinition();
						folderd.doMoveFolderDefinition(targetFolderDef, context);
					} else if (po instanceof DocumentDefinition) {
						DocumentDefinition documentDefinition = (DocumentDefinition) po;
						parentFolderDef = documentDefinition
								.getFolderDefinition();
						documentDefinition.doMoveFolderDefinition(
								targetFolderDef, context);
					}
					CTreeViewer viewer = (CTreeViewer) targetViewerControl
							.getViewer();
					viewer.refresh(targetFolderDef);
					if (parentFolderDef != null) {
						viewer.refresh(parentFolderDef);
					}
					// viewer.expandToLevel(targetFolderDef,
					// CTreeViewer.ALL_LEVELS);
				}
			}
		} catch (Exception e) {
			MessageUtil.showToast(e);
		}
		super.doDrop(sourceId, dragsItems, event, targetViewerControl);
	}

}
